// 主入口文件 - 时空回音游戏
class TimeEchoGame {
    constructor() {
        this.version = '1.0.0';
        this.isInitialized = false;
        this.loadingProgress = 0;
        
        this.init();
    }

    async init() {
        try {
            console.log('时空回音 - 游戏启动中...');
            
            // 显示加载进度
            this.updateLoadingProgress(10, '初始化系统...');
            
            // 等待DOM加载完成
            if (document.readyState === 'loading') {
                await new Promise(resolve => {
                    document.addEventListener('DOMContentLoaded', resolve);
                });
            }
            
            this.updateLoadingProgress(20, '加载资源...');
            
            // 初始化各个系统
            await this.initializeSystems();
            
            this.updateLoadingProgress(80, '准备游戏界面...');
            
            // 设置全局事件监听
            this.setupGlobalEvents();
            
            // 添加场景图片的CSS类支持
            this.setupSceneImages();
            
            this.updateLoadingProgress(90, '完成初始化...');
            
            // 标记初始化完成
            this.isInitialized = true;
            
            this.updateLoadingProgress(100, '欢迎来到时空回音！');
            
            console.log('时空回音 - 游戏初始化完成');
            
            // 触发游戏就绪事件
            window.dispatchEvent(new CustomEvent('gameReady'));
            
        } catch (error) {
            console.error('游戏初始化失败:', error);
            this.handleInitializationError(error);
        }
    }

    async initializeSystems() {
        const systems = [
            { name: 'i18n', instance: window.i18n },
            { name: 'saveSystem', instance: window.saveSystem },
            { name: 'gameEngine', instance: window.gameEngine },
            { name: 'achievementSystem', instance: window.achievementSystem },
            { name: 'storyManager', instance: window.storyManager },
            { name: 'uiManager', instance: window.uiManager }
        ];

        for (let i = 0; i < systems.length; i++) {
            const system = systems[i];
            this.updateLoadingProgress(
                30 + (i * 8), 
                `初始化 ${system.name}...`
            );
            
            // 等待系统初始化
            if (system.instance && typeof system.instance.init === 'function') {
                await system.instance.init();
            }
            
            // 验证系统是否正确加载
            if (!system.instance) {
                throw new Error(`系统 ${system.name} 加载失败`);
            }
            
            console.log(`✓ ${system.name} 系统已加载`);
        }
    }

    setupGlobalEvents() {
        // 全局错误处理
        window.addEventListener('error', (e) => {
            this.handleError(e.error);
        });

        window.addEventListener('unhandledrejection', (e) => {
            this.handleError(e.reason);
        });

        // 游戏状态事件
        window.addEventListener('gameReady', () => {
            this.onGameReady();
        });

        // 监听成就解锁
        window.addEventListener('achievementUnlocked', (e) => {
            this.onAchievementUnlocked(e.detail);
        });

        // 监听语言切换
        window.addEventListener('languageChanged', (e) => {
            this.onLanguageChanged(e.detail);
        });

        // 监听屏幕切换
        window.addEventListener('screenChanged', (e) => {
            this.onScreenChanged(e.detail);
        });

        // 性能监控
        this.setupPerformanceMonitoring();
    }

    setupSceneImages() {
        // 设置场景图片的动态类名映射，使用相对路径
        const sceneImageMap = {
            'images/lab_night.jpg': 'scene-img-lab-night',
            'images/data_screen.jpg': 'scene-img-data-screen', 
            'images/blue_glow.jpg': 'scene-img-blue-glow',
            'images/emergency_shutdown.jpg': 'scene-img-emergency',
            'images/scientific_discovery.jpg': 'scene-img-discovery',
            'images/portal_opened.jpg': 'scene-img-portal',
            'images/time_fusion.jpg': 'scene-img-fusion',
            'images/observer_effect.jpg': 'scene-img-observer',
            'images/team_safety.jpg': 'scene-img-team',
            'images/parallel_world.jpg': 'scene-img-parallel'
        };

        // 直接替换GameEngine的displayScene方法
        const originalDisplayScene = window.gameEngine.displayScene.bind(window.gameEngine);
        window.gameEngine.displayScene = function(sceneData) {
            // 调用原始方法
            originalDisplayScene(sceneData);
            
            // 更新图片显示
            const sceneImg = document.getElementById('sceneImg');
            const sceneImageContainer = document.querySelector('.scene-image');
            
            if (sceneImageContainer && sceneData.image) {
                // 清除之前的CSS类
                sceneImageContainer.className = 'scene-image';
                
                // 添加新的CSS类
                const cssClass = sceneImageMap[sceneData.image];
                if (cssClass) {
                    sceneImageContainer.classList.add(cssClass);
                    console.log(`✓ 场景图片类: ${cssClass}`);
                } else {
                    // 如果没有对应类，使用占位符图片
                    console.log(`🖼️ 使用占位符图片: ${sceneData.image}`);
                }
                
                // 设置实际图片路径，如果不存在则使用占位符
                if (sceneImg) {
                    sceneImg.onerror = function() {
                        this.src = 'images/placeholder.svg';
                        console.log('🖼️ 图片加载失败，使用占位符');
                    };
                    sceneImg.src = sceneData.image || 'images/placeholder.svg';
                    sceneImg.style.display = 'block';
                }
            }
        };
        
        console.log('✓ 场景图片系统已设置（支持本地运行）');
    }

    setupPerformanceMonitoring() {
        // 监控帧率
        let frameCount = 0;
        let lastTime = performance.now();
        
        const checkPerformance = () => {
            frameCount++;
            const currentTime = performance.now();
            
            if (currentTime - lastTime >= 5000) { // 每5秒检查一次
                const fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
                
                if (fps < 30) {
                    console.warn('游戏性能较低，FPS:', fps);
                    this.optimizePerformance();
                }
                
                frameCount = 0;
                lastTime = currentTime;
            }
            
            requestAnimationFrame(checkPerformance);
        };
        
        requestAnimationFrame(checkPerformance);
    }

    optimizePerformance() {
        // 性能优化措施
        console.log('启动性能优化...');
        
        // 减少动画
        const animationElements = document.querySelectorAll('[style*="animation"]');
        animationElements.forEach(el => {
            el.style.animationDuration = '0.1s';
        });
        
        // 简化背景效果
        const particles = document.querySelector('.bg-particles');
        if (particles) {
            particles.style.display = 'none';
        }
    }

    updateLoadingProgress(percentage, message) {
        this.loadingProgress = percentage;
        
        // 更新加载界面
        const loadingText = document.querySelector('#loadingScreen p');
        if (loadingText) {
            loadingText.textContent = message;
        }
        
        // 可以在这里添加进度条更新
        console.log(`加载进度: ${percentage}% - ${message}`);
    }

    onGameReady() {
        console.log('🎮 游戏准备完毕!');
        
        // 验证系统状态
        this.validateSystems();
        
        // 初始化扩展系统
        this.initializeExtensionSystems();
        
        // 检查是否有自动加载的存档
        this.checkAutoLoad();
        
        // 显示版本信息
        this.displayVersionInfo();
    }
    
    initializeExtensionSystems() {
        console.log('🚀 初始化扩展系统...');
        
        // 合并扩展成就到原有系统
        if (window.extendedAchievements && window.achievementSystem) {
            window.extendedAchievements.mergeWithOriginalAchievements();
        }
        
        // 初始化结局管理器
        if (window.endingsManager) {
            console.log('✓ 结局管理器已加载，共', Object.keys(window.endingsManager.endings).length, '个结局');
        }
        
        // 验证扩展数据
        if (window.extendedStoryData) {
            console.log('✓ 扩展剧情数据已加载，包含5个章节');
        }
        
        console.log('🎉 扩展系统初始化完成！');
        console.log('📊 游戏统计：');
        console.log('  - 总成就数：', window.achievementSystem ? Object.keys(window.achievementSystem.achievements).length : 0);
        console.log('  - 总结局数：', window.endingsManager ? Object.keys(window.endingsManager.endings).length : 0);
        console.log('  - 章节数：5个完整章节');
        console.log('  - 支持语言：中文 + English');
    }
    
    validateSystems() {
        const systems = {
            uiManager: window.uiManager,
            gameEngine: window.gameEngine,
            i18n: window.i18n,
            achievementSystem: window.achievementSystem,
            storyManager: window.storyManager,
            saveSystem: window.saveSystem
        };
        
        console.log('系统验证结果:');
        Object.entries(systems).forEach(([name, system]) => {
            const status = system ? '✓ 正常' : '❌ 未加载';
            console.log(`  ${name}: ${status}`);
        });
        
        // 检查按钮绑定
        const buttons = ['newGameBtn', 'continueBtn', 'achievementsBtn', 'timelineBtn', 'settingsBtn'];
        console.log('按钮元素检查:');
        buttons.forEach(btnId => {
            const btn = document.getElementById(btnId);
            const status = btn ? '✓ 存在' : '❌ 缺失';
            console.log(`  ${btnId}: ${status}`);
        });
    }

    checkAutoLoad() {
        // 检查URL参数是否有自动加载指令
        const urlParams = new URLSearchParams(window.location.search);
        const autoLoad = urlParams.get('autoload');
        
        if (autoLoad === 'true' && window.saveSystem.hasSaveData()) {
            setTimeout(() => {
                if (window.uiManager.getCurrentScreen() === 'mainMenu') {
                    window.uiManager.handleContinueGame();
                }
            }, 1000);
        }
    }

    displayVersionInfo() {
        // 在控制台显示版本信息
        console.log(`
🌟 时空回音 (Time Echo) v${this.version}
📅 构建时间: ${new Date().toLocaleString()}
🎯 比赛版本: VIBE25-3
💡 技术栈: HTML5 + CSS3 + Vanilla JavaScript
🌍 多语言: 中文 + English
        `);
    }

    onAchievementUnlocked(detail) {
        console.log('🏆 成就解锁:', detail.achievementId);
        
        // 可以在这里添加全局的成就解锁效果
        this.triggerGlobalCelebration();
    }

    triggerGlobalCelebration() {
        // 触发全局庆祝效果
        document.body.style.animation = 'celebration 0.5s ease-in-out';
        
        setTimeout(() => {
            document.body.style.animation = '';
        }, 500);
    }

    onLanguageChanged(detail) {
        console.log('🌐 语言切换到:', detail.language);
        
        // 更新页面标题
        document.title = detail.language === 'zh' ? '时空回音 - Time Echo' : 'Time Echo - 时空回音';
    }

    onScreenChanged(detail) {
        console.log(`📱 屏幕切换: ${detail.from} → ${detail.to}`);
        
        // 可以在这里添加屏幕切换的统计或特效
    }

    handleError(error) {
        console.error('游戏错误:', error);
        
        // 错误报告和恢复
        if (this.isInitialized) {
            this.showErrorDialog(error);
        } else {
            this.handleInitializationError(error);
        }
    }

    handleInitializationError(error) {
        console.error('初始化错误:', error);
        
        // 显示错误页面
        document.body.innerHTML = `
            <div style="
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                height: 100vh;
                background: var(--bg-dark);
                color: var(--text-primary);
                text-align: center;
                padding: 20px;
            ">
                <h1 style="color: var(--secondary-color); margin-bottom: 20px;">
                    游戏加载失败
                </h1>
                <p style="margin-bottom: 20px;">
                    抱歉，游戏在初始化过程中遇到了问题。
                </p>
                <p style="font-size: 14px; opacity: 0.7; margin-bottom: 30px;">
                    错误信息: ${error.message}
                </p>
                <button 
                    onclick="window.location.reload()" 
                    style="
                        background: var(--primary-color);
                        border: none;
                        color: white;
                        padding: 12px 24px;
                        border-radius: 8px;
                        cursor: pointer;
                        font-size: 16px;
                    "
                >
                    重新加载游戏
                </button>
            </div>
        `;
    }

    showErrorDialog(error) {
        if (window.uiManager) {
            window.uiManager.showNotification(`发生错误: ${error.message}`, 'error');
        }
    }

    // 游戏控制方法
    restart() {
        console.log('重启游戏...');
        
        // 重置所有系统
        if (window.gameEngine) window.gameEngine.startNewGame();
        if (window.storyManager) window.storyManager.reset();
        if (window.uiManager) window.uiManager.showMainMenu();
    }

    save() {
        if (window.gameEngine) {
            window.gameEngine.saveGame();
        }
    }

    load() {
        if (window.gameEngine) {
            return window.gameEngine.loadGame();
        }
        return false;
    }

    // 诊断和调试
    getDiagnosticInfo() {
        return {
            version: this.version,
            isInitialized: this.isInitialized,
            loadingProgress: this.loadingProgress,
            currentScreen: window.uiManager ? window.uiManager.getCurrentScreen() : 'unknown',
            gameState: window.gameEngine ? window.gameEngine.getGameState() : null,
            storyInfo: window.storyManager ? window.storyManager.getDebugInfo() : null,
            storageInfo: window.saveSystem ? window.saveSystem.diagnoseStorage() : null,
            achievements: window.achievementSystem ? {
                unlocked: window.achievementSystem.getUnlockedCount(),
                total: window.achievementSystem.getTotalCount(),
                percentage: window.achievementSystem.getUnlockedPercentage()
            } : null
        };
    }

    // 开发者工具
    enableDebugMode() {
        window.DEBUG_MODE = true;
        console.log('🛠️ 调试模式已启用');
        
        // 添加调试快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.shiftKey) {
                switch (e.key) {
                    case 'D':
                        console.log('诊断信息:', this.getDiagnosticInfo());
                        break;
                    case 'R':
                        this.restart();
                        break;
                    case 'S':
                        this.save();
                        break;
                    case 'L':
                        this.load();
                        break;
                }
            }
        });
    }
}

// 添加庆祝动画样式
const celebrationStyle = document.createElement('style');
celebrationStyle.textContent = `
    @keyframes celebration {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.02); }
    }
`;
document.head.appendChild(celebrationStyle);

// 引入场景样式
const sceneStyleLink = document.createElement('link');
sceneStyleLink.rel = 'stylesheet';
sceneStyleLink.href = 'css/scenes.css';
document.head.appendChild(sceneStyleLink);

// 创建全局游戏实例
window.timeEchoGame = new TimeEchoGame();

// 开发环境下启用调试模式
if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    window.timeEchoGame.enableDebugMode();
}

// 导出到全局作用域供调试使用
window.game = window.timeEchoGame;